<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" @submit.native.prevent>
      <el-form-item label="权限表" prop="tableName">
        <el-input v-model="queryParams.tableName" placeholder="请输入权限表名称" clearable size="small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="() => handleDialog('add')"
          v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
    </el-row>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table v-loading="loading" :data="roleList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="表格名称" prop="name" width="320" />
      <el-table-column label="表格描述" prop="TABLE_COMMENT" width="320" />
      <!-- <el-table-column label="表格类型" prop="TABLE_TYPE" :show-overflow-tooltip="true" width="250" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['system:role:edit']"
            @click="() => handleDialog('updata', scope.row)">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click=""
            v-hasPermi="['system:role:edit']">详情</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getAccessTables" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!--  :model="form" -->
      <el-form ref="form" :rules="rules" label-width="100px" :model="form">
        <el-form-item label="表格名称" prop="TABLE_NAME">
          <el-select filterable v-model="TABLE_NAME" placeholder="请选择表格名称" size="small" :disabled="tableNameFlag">
            <el-option v-for="dict in statusOptions" :label="dict.label" :key="dict.value"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!--  @tab-click="handleClick" -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="批量操作" name="first" :disabled="tableMightFlag">
            <el-form-item label="表格权限" prop="TABLE_COMMENT">
              <el-checkbox ref="check" :indeterminate="isIndeterminate" v-model="checkAll"
                @change="handleCheckAllChange">全选/全不选</el-checkbox>
              <div style="margin: 15px 0;"></div>
              <!-- @change="handleCheckedCitiesChange" -->
              <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="city in cities" :label="city.type" :key="city.label">{{ city.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="单独设置" name="second">
            <el-table :data="tableData" style="width: 100%" ref="myTable" v-loading="tableLoading">
              <el-table-column v-for="item in column" :prop="item.key" :label="item.label" :key="item.key">
                <template slot-scope="scope">
                  <template v-if="(item.key.includes('Role'))">
                    <!-- <span>{{ scope.row[item.key] ? '1' : '2' }}</span> -->
                    <el-switch v-model="scope.row[item.key]">
                    </el-switch>
                  </template>
                  <template v-else>
                    <span>{{ scope.row[item.key] }}</span>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-form-item label="权限分配" v-if="activeName == 'first'">
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id" empty-text="加载中，请稍后"
            :props="defaultProps"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccessTables, listRole, addTablesManagement, getTable, updateAccess } from "@/api/formRightsManagement";
const cityOptions = [{ type: 1, label: '增' }, { type: 2, label: '删' }, { type: 3, label: '改' }, { type: 4, label: '查' }];
export default {
  name: "formRightsManagement",
  data() {
    return {
      column: [
        { key: 'roleName', label: `角色` },
        { key: 'addRoleIds', label: `增` },
        { key: 'deleteRoleIds', label: `删` },
        { key: 'editRoleIds', label: `改` },
        { key: 'queryRoleIds', label: `查` }
      ],
      tableData: null,
      tabPosition: 'left',
      tabs: '1',
      TABLE_NAME: '',
      // tabs 
      activeName: 'second',
      // 遮罩层
      loading: true,
      tableLoading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 数据表
      statusOptions: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: undefined,
        roleKey: undefined,
        tableType: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {},
      checkAll: false,
      checkedCities: [],
      cities: cityOptions,
      isIndeterminate: false,
      tableMightFlag: false, //false 表示使用新增权限，true 表示使用编辑权限
      id: "", // 当前行的id，用于编辑权限时获取当前行的数据
      tableNameFlag: false
    };
  },
  created() {
    this.getAccessTables();
  },
  watch: {
    TABLE_NAME: function (val) {
      this.$nextTick(() => {
        if (val) this.getAccessTable({ tableName: val, type: 1 })
      })
    },
    activeName: function (val) {
      this.getMenuTreeselect()
    }
  },
  methods: {
    handleClick() {
      this.reset()
      if (this.activeName === 'second') {
        this.getAccessTable({ tableName: this.TABLE_NAME, type: 1 })
      }
    },
    async getTables() {
      await getTable().then(response => {
        if (response.code === 200) {
          this.menuOptions = []
          var modified = response.rows.map(function (obj) {
            var newObj = {};
            newObj.value = obj.TABLE_NAME;
            newObj.label = obj.TABLE_NAME;
            return newObj;
          });
          this.menuOptions = modified
          this.statusOptions = modified
        }
      })
    },
    /** 查询权限表 */
    getAccessTables() {
      this.loading = true;
      getAccessTables(this.queryParams).then(
        response => {
          this.tableMightFlag = false;
          this.roleList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询弹框权限表 */
    getAccessTable(params) {
      this.tableLoading = true
      getAccessTables(params).then(
        response => {
          if (response.code === 200) {
            if (response.rows.length > 0) {
              this.id = response.rows[0].id;
              this.activeName = 'second'
              this.tableMightFlag = true;
            } else {
              this.tableMightFlag = false;
              this.id = '';
            }
            if (this.activeName == 'second') {
              let result = this.menuOptions.map(obj => {
                let role = {
                  id: obj.id,
                  roleName: obj.roleName || obj.label,
                  addRoleIds: false,
                  deleteRoleIds: false,
                  editRoleIds: false,
                  query_role_ids: false,
                };

                for (let item of response.rows) {
                  let deleteRoleIds = item.delete_role_ids?.split(',') || [];
                  let queryRoleIds = item.query_role_ids?.split(',') || [];
                  let editRoleIds = item.edit_role_ids?.split(',') || [];
                  let addRoleIds = item.add_role_ids?.split(',') || [];

                  if (deleteRoleIds.includes(obj.id?.toString())) {
                    role.deleteRoleIds = true;
                  }
                  if (queryRoleIds.includes(obj.id?.toString())) {
                    role.queryRoleIds = true;
                  }
                  if (editRoleIds.includes(obj.id?.toString())) {
                    role.editRoleIds = true;
                  }
                  if (addRoleIds.includes(obj.id?.toString())) {
                    role.addRoleIds = true;
                  }
                }
                return role;
              });
              let that = this;
              setTimeout(() => { that.tableData = result; }, 500);
            }
            this.tableLoading = false
          }
        }
      ).catch(error => {
        console.error('Error fetching access tables:', error);
      });
    },

    /** 全选查询角色 */
    getMenuTreeselect() {
      listRole().then(response => {
        if (response.code == 200 && response.rows.length > 0) {
          let fg = this.activeName === 'first' ? true : false;
          this.tableData = []
          var modifiedObjArr = response.rows.map(function (obj) {
            var newObj = {};
            newObj.id = obj.roleId;
            if (fg) {
              newObj.label = obj.roleName;
            } else {
              newObj.roleName = obj.roleName;
            }
            return newObj;
          });
          this.tableData = modifiedObjArr;
          this.menuOptions = modifiedObjArr
        }
      });
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      if (this.$refs.menu) {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      }
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      if (this.$refs.dept) {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getCheckedKeys();
        // 半选中的部门节点
        let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.checkAll = false;
      this.checkedCities = [];
      this.menuNodeAll = false;
      this.deptExpand = true;
      this.deptNodeAll = false;
      this.tableNameFlag = false;
      this.form = {
        roleId: undefined,
        tableName: undefined,
        roleKey: undefined,
        roleSort: 0,
        tableType: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined
      };
      this.resetForm("form");
      !this.open ? (this.TABLE_NAME = '') : ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getAccessTables();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      }
    },

    /** 新增按钮操作 */
    handleDialog(flag, row) {
      this.getTables();
      this.tableMightFlag = flag == 'add' ? false : true;
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = flag == 'add' ? '权限新增' : '权限修改'
      this.activeName = flag == 'add' ? 'first' : 'second'
      this.TABLE_NAME = row.name;
      this.tableNameFlag = flag == 'add' ? false : true;
      this.getAccessTable({ tableName: row.name || '', type: 1 })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      this.title = "修改角色";
    },

    /** 提交按钮 */
    submitForm: function () {
      const tableInstance = this.$refs.myTable;
      const tableData = tableInstance.data;
      let idList = {
        addRoleIds: '',
        deleteRoleIds: '',
        editRoleIds: '',
        queryRoleIds: '',
      }
      tableData.map(item => {
        // 获取表格中的true值
        for (let key in item) {
          if (item[key] === true && item[key] != 'id' && item[key] != 'roleName') {
            idList[key] += item.id + ','
          }
        }
      })
      let that = this;
      var typeList = ['addRoleIds', 'deleteRoleIds', 'editRoleIds', 'queryRoleIds'];
      let params = {
        tableName: this.TABLE_NAME
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.menuIds = this.getMenuAllCheckedKeys();
          if (this.form.menuIds != undefined) {
            that.checkedCities.map(function (item) {
              typeList.map((item1, index1) => {
                if ((item - 1) == index1) {
                  params[typeList[item - 1]] = that.form.menuIds.join(',')
                }
              })
            })
          }
        }
        if (this.activeName == 'first') {
          // console.log('1111', params);
        } else {
          params = { ...params, ...idList }
          // console.log('paramss', params);
        }
        console.log('paramss', params);
        if (!this.tableMightFlag) {
          // 新增
          addTablesManagement(params).then(response => {
            if (response.code === 200) {
              this.msgSuccess("添加成功");
              this.open = false;
              this.checkedCities = [];
              this.isIndeterminate = false;
              this.TABLE_NAME = '';
              this.getAccessTables();
            }
          })
        } else {
          // 修改
          params.id = this.id;
          let formData = new FormData();
          for (let key in params) {
            formData.append(key, params[key]);
          }
          updateAccess(formData).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.open = false;
              this.checkedCities = [];
              this.isIndeterminate = false;
              this.TABLE_NAME = '';
              this.getAccessTables();
            }
          })
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有角色数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportRole(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => { });
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? [1, 2, 3, 4] : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    }
  },
};
</script>

<style  scoped>
::v-deep .el-tabs__nav-scroll {
  margin-left: 30px !important;
}
</style>